var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var Map = require("../../../utils/map.js");

// 获取地图的返回信息
const chooseLocation = requirePlugin('chooseLocation');

const BACK = "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/Leader/id_bg.png",
    POSITIVE = "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/Leader/id_country.png";
Page({
    /**
     * 页面的初始数据
     */
    data: {
		// region: ['广东省', '广州市', '海珠区'],
        region: [],
        isClearShow: false,
        hasStorefront: true,
        // address: data.id,
        back: BACK, //反面身份证
        // hasStorefront: true,
        // lat: 0,
        // leaderName: 0,
        // lon: 0,
        // memberId: 0,
        // phone: 0,
        positive: POSITIVE, //正面身份证
        // username: "",
        // village: "",
        showPhoneValid: false,
        phone: "",
        location: {
            latitude: 0,
            longitude: 0
        },
        mapName: "",
        mapDetail: "",
        areaArr:[],
        areaIndex:null,
        leaderId:'',
        activityId:''
	},
    bindPickerChange(e){
        console.log(e)
        this.setData({
            areaIndex: e.detail.value
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this
        if(options.leaderId != undefined){
            that.setData({
                leaderId:options.leaderId,
                activityId:options.activityId
            })
        } else if(wx.getStorageSync('leaderId') != undefined){
            that.setData({
                leaderId:wx.getStorageSync('leaderId'),
                activityId:wx.getStorageSync('activityId')
            })
        }
        console.log(that.data.leaderId,that.data.activityId)
        this.getDistList()
    },
    getDistList() {
        let that = this
        wx.showLoading({
            title: "正在加载...",
        });
        util.request(api.leader.distList, {}, "GET")
            .then((res) => {
                wx.hideLoading();
                that.setData({
                    areaArr:res.result
                })
            })
            .catch((err) => {
                wx.hideLoading();
            });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const location = chooseLocation.getLocation();
        if(location){
            let mapName = location.province + location.city + location.district;
            
            console.log("123");
            if(!mapName){
                mapName = location.address.split(location.name)[0] || ""
            }
            const mapDetail = location.address.split(location.district)[1] + location.name;
            this.setData({
                location,
                mapName: mapName || "",
                mapDetail: mapDetail || ""
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        chooseLocation.setLocation(null);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    // 地图事件
    toMap(){
        Map.getAddress(this.data.location);
    },
    // 手机事件 开始
    clearHide: function(e){
        const value = this.data.phone;
        if(!(/^1[0-9]{10}$/.test(value))){
            this.setData({
                showPhoneValid: true,
            })
        }else{
            if(this.data.showPhoneValid){
                this.setData({
                    showPhoneValid: false
                })
            }
        }
        this.setData({
            isClearShow: false,
        })
    },
    clearShow: function(e){
        this.setData({
            showPhoneValid: false,
            isClearShow: true,
        })
    },
    clearPhone: function(e){
        this.setData({
            phone: ""
        })
    },
    phoneInput: function(e){
        this.setData({
            phone: e.detail.value
        })
    },
    // 手机事件 结束

    radioChange: function(e){
        this.setData({
            hasStorefront: e.detail.value == 1 ? true : false
        })
    },
    // 后台请求
    applyMember(data){
        wx.showLoading({
            title: "正在提交中",
            icon: "none"
        })
        util.request(
            api.leader.applyMemberLeaderUrl,
            data,
            "POST"
        ).then(res=>{
            console.log("ress", res);
            wx.hideLoading();
            // wx.showToast({
            //     title: res.message,
            //     icon: "none"
            // })
            let templIds = ['x3i9DaBhYRPICPpUbczHGRbPhzPqyglGhY_3IuPnwDI']
            wx.requestSubscribeMessage({
                tmplIds: templIds,
                success (res) {
                    console.log(res)
                    wx.redirectTo({
                        url: "/Leader/application/application-result/application-result"
                    })
                },
                fail (err) {
                    console.log(err)
                    wx.redirectTo({
                        url: "/Leader/application/application-result/application-result"
                    })
                }
            })
        }).catch(err=>{
            console.log("err", err);
            wx.hideLoading();
            wx.showToast({
                title: err.message,
                icon: "none"
            })
        })
    },
    // 提交表单
    formSubmit: function(e){
        const result = this.validForm(e.detail.value);
        console.log(this.getParams(e.detail.value))
        if(result){
            // 验证成功
            const data = this.getParams(e.detail.value);
            this.applyMember(data);
        }
    },
    // 表单验证
    validForm(values){
        let keys = [];//必填选项
        const { hasStorefront, location, back, positive } = this.data;
        if(hasStorefront){
            // 有门店
            keys = ["leaderName", "phone", "village", "storeName"] ; //必填选项

        }else{
            // 没门店
            keys = ["leaderName", "phone"] ; 
        }
        const result = keys.every(item => values[item]);
        if(!result){
            wx.showToast({
                title: "还有选项没填哦",
                icon: "none"
            })
            return false;
        }
        if(this.data.areaIndex == null){
            wx.showToast({
                title: "请选择区域",
                icon: "none"
            })
            return false;
        }
        if(hasStorefront){
            if(location.latitude == 0){
                wx.showToast({
                    title: "所在位置还没选哦",
                    icon: "none"
                })
                return false;
            }
        }
        if(back === BACK || positive === POSITIVE){
            wx.showToast({
                title: "身份证还没上传完哦",
                icon: "none"
            })
            return false;
        }
        return true;
    },
    // 参数处理
    getParams(values){
        const { location, back, positive,activityId,leaderId,isMine,areaArr,areaIndex } = this.data;
        const userInfo = wx.getStorageSync("userInfo");
        let defaultData = {
            "address": "",
            "back": back,
            "hasStorefront": true,
            "isSupportFreeze": true,
            "lat": location.latitude,
            "leaderName": "",
            "lon": location.longitude,
            "memberId": userInfo.id || 0,
            "phone": "",
            "positive": positive,
            "storeAddress": "",
            "storeImage": "",
            "storeName": "",
            "username": userInfo.nikeName || "",
            "village": "",
            "workerLeaderName": "",
            "workerMemberId": 0,
            "activityId": activityId,
            "parentLeaderId":leaderId,
            "distId": areaArr[areaIndex].id
        };
        values.hasStorefront = values.hasStorefront == 1 ? true : false;
        values.isSupportFreeze = values.isSupportFreeze == 1 ? true : false;
        return Object.assign(defaultData, values)
    },
    // 预览图片
    gotoShow: function(e){
        const _this = this;
        const {type} = e.currentTarget.dataset;
        wx.chooseImage({
            count: 1, // 最多可以选择的图片张数，默认9
            sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
            sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
            success: function(res){
                // success
                wx.showLoading({
                    title: "正在上传中"
                })
                wx.uploadFile({
                    url: api.leader.uploadImageUrl, //仅为示例，非真实的接口地址
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    formData: {
                      'user': type
                    },
                    success (result){
                        wx.hideLoading();
                        if(result.statusCode === 413){
                            return wx.showToast({
                                title: "图片太大了",
                                icon: "error"
                            })
                        }
                        result.data = JSON.parse(result.data);
                        const data = result.data.message;
                        _this.setData({
                            [type]: data
                        })
                    }
                })
            },
            fail: function() {
                // fail
            },
            complete: function() {
            // complete
            }
        })
    }
});
